package com.zhongxi.guoyuan.view.user;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.code.CodeResult;
import com.zhongxi.guoyuan.entity.user.RegisterCheckResult;
import com.zhongxi.guoyuan.entity.user.UserData;
import com.zhongxi.guoyuan.entity.user.UseInfo;
import com.zhongxi.guoyuan.entity.user.UserResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.RegularTool;
import com.zhongxi.guoyuan.view.MainHomeActivity;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private EditText etPhone;
    private EditText etCode;
    private EditText etShoper;
    private Button btSend;
    private Button bt_noRegister;
    private Button btRegister;
    private Map<String, String> map = new HashMap<String, String>();
    private String phone;
    private String code;
    private String type;
    private CheckBox cb;
    private TextView tvAgreement;
    private String mUseid;
    private String mMsgid;
    private String mShoper;
    private LinearLayout mLl_shopper;


    /*定义一个倒计时的内部类*/
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长，和计时的时间间隔
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            btSend.setClickable(false);
            btSend.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {//计时完毕时触发
            btSend.setText("发送验证码");
            btSend.setClickable(true);
        }

    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_register);
        initTitle();
        tvTitle.setText("注册会员");
        if (getIntent() != null) {
            mUseid = getIntent().getStringExtra("useid");
        }
        etPhone = (EditText) findViewById(R.id.etPhone);
        etCode = (EditText) findViewById(R.id.etCode);
        etShoper = (EditText) findViewById(R.id.etShoper);
        btSend = (Button) findViewById(R.id.btSend);
        bt_noRegister = (Button) findViewById(R.id.bt_noRegister);
        btRegister = (Button) findViewById(R.id.btRegister);
        tvAgreement = (TextView) findViewById(R.id.tvAgreement);
        mLl_shopper = (LinearLayout) findViewById(R.id.ll_shopper);
        cb = (CheckBox) findViewById(R.id.cb);
        if (!TextUtils.isEmpty(MyApplication.getInstance().getAppOpenid())) {
            mLl_shopper.setVisibility(View.VISIBLE);
            bt_noRegister.setVisibility(View.VISIBLE);
            btRegister.setText("下一步");
        } else {
            mLl_shopper.setVisibility(View.GONE);
            bt_noRegister.setVisibility(View.GONE);
            btRegister.setText(getString(R.string.bt_register));
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    private void getValue() {
        phone = etPhone.getText().toString().trim();
        code = etCode.getText().toString().trim();
        mShoper = etShoper.getText().toString().trim();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        btSend.setOnClickListener(this);
        bt_noRegister.setOnClickListener(this);
        btRegister.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        tvAgreement.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btSend:
                sendCode();
                break;
            case R.id.btRegister:
                register();
                break;
            case R.id.bt_noRegister:
                noRegister();
                break;
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvAgreement:
                startAct(AgreementActivity.class);
                break;
        }
    }


    /**
     * 发送验证码
     */
    @SuppressLint("NewApi")
    private void sendCode() {
        getValue();
        if (TextUtils.isEmpty(phone)) {
            showShortToast("手机号不能为空");
        } else if (!RegularTool.isPhoneNumberValid(phone)) {
            showShortToast("请输入正确的手机号");
        } else {
            type = "sendcode";
            TimeCount time = new TimeCount(60000, 1000);
            time.start();
            map.clear();
            map.put("mobilenum", phone);
            getServer(Url.SEND_CODE, map, "", false, null, "post");
        }
    }

    /**
     * 未绑定手机
     */
    private void noRegister() {
        map.clear();
        type = "noRegisterCheck";
        map.put("openid", MyApplication.getInstance().getAppOpenid());
        getServer(Url.WXNOBINDING, map, "", false, null, "post");

    }

    /**
     * 注册
     */
    private void register() {
        getValue();
        if (TextUtils.isEmpty(phone)) {
            showShortToast("手机号不能为空");
        } else if (TextUtils.isEmpty(code)) {
            showShortToast("验证码不能为空");
        } else if (!RegularTool.isPhoneNumberValid(phone)) {
            showShortToast("请输入正确的手机号");
        } else if (!cb.isChecked()) {
            showShortToast("请先同意注册条款");
        } else {
            type = "registerCheck";
            map.clear();
            map.put("mobilenum", phone);
            map.put("veriycode", code);
            map.put("msgid", mMsgid);
            if (!TextUtils.isEmpty(MyApplication.getInstance().getAppOpenid())) {
                map.put("openid", MyApplication.getInstance().getAppOpenid());
                if (!TextUtils.isEmpty(mShoper)) {
                    map.put("invitationcode", mShoper);
                }
                if (!TextUtils.isEmpty(mUseid)) {  // 微信老用户未绑定手机的
                    map.put("useid", mUseid);
                }
                getServer(Url.WXCHECKPHONE, map, "", false, null, "post");
            } else {
                getServer(Url.REGISTER_CHECK, map, "", false, null, "post");
            }
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if ("sendcode".equals(type)) {
            CodeResult result = gson.fromJson(response, CodeResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            mMsgid = result.getMsgid();  // 短信唯一标识
        } else if ("registerCheck".equals(type)) {
            RegisterCheckResult result = gson.fromJson(response, RegisterCheckResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            Intent mIntent = new Intent(this, SetPasswordActivity.class);
            mIntent.putExtra("id", result.getId());
            startActivity(mIntent);
        } else if ("noRegisterCheck".equals(type)) {
            UserResult result = gson.fromJson(response, UserResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            if (null != result.getData() && !"".equals(result.getData())) {
                UserData data = result.getData();
                MyApplication.getInstance().sharedPrefrences.edit().putString("phone", result.getData().getMphone()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("userid", result.getData().getId()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("username", result.getData().getUsername()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", result.getData().getShopname()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", result.getData().getAvatar()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("time", result.getData().getCtime()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", result.getData().getAppopenid()).commit();
                if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  //股东
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", "1".equals(data.getIsshareholders())).commit();
                }
                if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  // 消费收益人
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", "1".equals(data.getIsbeneficiary())).commit();
                }
                if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  //商家
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", "1".equals(data.getIsmerchants())).commit();
                }

                if (null != String.valueOf(data.getIspartner())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("partener", 1 == data.getIspartner()).commit();
                }
                JPushInterface.setAlias(context, MyApplication.getInstance().getUserId(), new TagAliasCallback() {
                    @Override
                    public void gotResult(int i, String s, Set<String> set) {
                    }
                });
            }
            if (null != result.getExtend() && !"".equals(result.getExtend())) {
                UseInfo extend = result.getExtend();
                if (null != extend.getInnercurrency() && !"".equals(extend.getInnercurrency())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("inner", extend.getInnercurrency()).commit();
                }
                if (!TextUtils.isEmpty(extend.getRedbean())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("hd", extend.getRedbean()).commit();
                }

                if (null != extend.getSharesgains() && !"".equals(extend.getSharesgains())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("share", extend.getSharesgains()).commit();  //股份收益
                }
            }
            finish();
            startAct(MainHomeActivity.class);
        }
    }


    @Override
    public void processOldUser(String response) {
        super.processOldUser(response);
        Gson gson = new Gson();
        RegisterCheckResult result = gson.fromJson(response, RegisterCheckResult.class);
        if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        showShortToast("老用户需设置密码");
        Intent mIntent = new Intent(this, SetPasswordActivity.class);
        mIntent.putExtra("id", result.getId());
        startActivity(mIntent);
        finish();
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse mBaseResponse = gson.fromJson(response, BaseResponse.class);
            MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
            int errorcode = mBaseResponse.getCode();
            if (errorcode == 1000) {
                showShortToast("参数错误");
            } else if (errorcode == 1010) {
                showShortToast("店铺名或手机号已被抢注,请更换后重试");
            } else if (errorcode == 1100) {
                showShortToast("短信重复请求");
            } else if (errorcode == 1101) {
                showShortToast("短信服务失效");
            } else if (errorcode == 4001) {
                showShortToast("老用户,可直接登陆");
                finish();
                startAct(LoginActivity.class);
            } else if (errorcode == 1003) {
                showShortToast("用户已登录");
            } else if (errorcode == 1006) {
                showShortToast("邀请码错误");
            } else if (errorcode == 1007) {  // 用户成功
                Intent mIntent = new Intent(this, SetPasswordActivity.class);
                mIntent.putExtra("id", mBaseResponse.getId());
                startActivity(mIntent);
                finish();
            } else if (errorcode == 1008) {   // 商户成功
                Intent mIntent = new Intent(this, StoreSetActivity.class);
                mIntent.putExtra("id", mBaseResponse.getId());
                mIntent.putExtra("merchantsCode", mBaseResponse.getMerchantsCode());
                startActivity(mIntent);
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
